package dao.impl;

import dao.ProductDao;
import domain.Product;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.log4j.Logger;
import utils.C3P0Utils;

import java.sql.SQLException;
import java.util.List;

/**
 * @Author admin
 * @Date 2019/2/25 9:19
 */
public class ProductDaoImpl implements ProductDao {

    @Override
    public List<Product> findAll() {
        //参数是数据源（连接池），而不是连接对象
        QueryRunner runner = new QueryRunner(C3P0Utils.getDataSource());
        String sql = "SELECT * FROM product ORDER BY pdate DESC ";
        try {
           return runner.query(sql,new BeanListHandler<Product>(Product.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public int deleteProduct(int pid) {
        //参数是数据源（连接池），而不是连接对象
        QueryRunner runner = new QueryRunner(C3P0Utils.getDataSource());
        String sql = "DELETE FROM product WHERE pid = ?";
        try {
            return runner.update(sql,pid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public int addProduct(Product product) {

        QueryRunner runner = new QueryRunner(C3P0Utils.getDataSource());
        //我省略了，你不要省略
        String sql =  "INSERT INTO product (pname,marketprice,shopprice,...) VALUE (?,?,?)";
        try {
           return runner.update(sql,product.getPname(),product.getMarketprice());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

}
